let fs = require('fs');
let path = require('path');//解析需要遍历的文件夹

/**
 * 自动生成 vueComponent 组件配置
 */
function vueComponent(opts) {
  const filePath = path.resolve(opts.src);
  // console.log(filePath.replace(/\\/g, '/'))
  const arr = [];
  readFile(filePath, arr)
  const components = []
  arr.forEach(function (file) {
    let c = {}
    c.component = file.replace(filePath, '').replace('.vue', '');
    let index = c.component.lastIndexOf('/')
    c.name = c.component.substring(index == -1 ? 0 : index)

    if (c.name.includes('index')) {
      let tmp = c.component.replace('/index', '')
      tmp = tmp.substring(tmp.lastIndexOf('/')).replace('/', '')
      c.name = tmp.substring(0, 1).toUpperCase() + tmp.substring(1)
    }
    c.name = c.name.replace('/', '');
    // console.log(JSON.stringify(c))
    components.push(c)
  })
  return components;
}

function readFile(path, arr) {
  const files = fs.readdirSync(path)
  files.forEach(function (file) {
    const state = fs.statSync(`${path}/${file}`);
    if (state.isDirectory()) {
      return readFile(`${path}/${file}`, arr);
    } else {
      arr.push(`${path}/${file}`)
    }
  })
  return arr;
}

module.exports = options => {
  let opts = Object.create(options || null)
  opts.src = opts.src || './src/views'
  opts.filename = opts.filename || './src/utils/component-data.js'
  const res = vueComponent(opts)
  const str = "module.exports = "+JSON.stringify(res, null, 4)
  try {
    const content = fs.readFileSync(opts.filename)
    if(content.toString() === str){
      console.log(`no change ${opts.filename}`)
    }else{
      fs.writeFileSync(opts.filename,str)
      console.log(`create file ${opts.filename}`)
    }
  }catch (e) {

  }

}

